import { polarPoints } from '../../algorithm/polar.js'
import { _rotate, plainMatrix } from "../../math/index.js";
import { createPathFn } from "../path2.js";
import { eachNext } from "../../utils/index.js";

const turnout = (p1, p2) => {
    let [x1, y1] = p1
    let [x2, y2] = p2
    let x3 = (x2 - x1) / 3 + x1;
    let y3 = (y2 - y1) / 3 + y1;
    let x4 = (x2 - x1) / 3 * 2 + x1;
    let y4 = (y2 - y1) / 3 * 2 + y1;
    let p5 = _rotate([x4, y4], [x3, y3], -60)
    return [p1, [x3, y3], p5, [x4, y4], p2]
    // return [p1, [x3, y3], [...p5,x4, y4], p2]
}
export const kochPoints = (options = {}) => {
    let { o = [300, 200], r = 200, n = 3, depth = 3, a = 0 } = options
    let points = polarPoints({
        o, r, n, a
    })
    let _iter = (ps, depth) => {
        let len = ps.length
        if (depth === 0) {
            let result = ps.map((t, index) => {
                let next = ps[(index + 1) % len]
                return turnout(t, next)
            });
            return plainMatrix(result)
        } else {
            let result = ps.map((t, index) => {
                let next = ps[(index + 1) % len]
                return _iter(turnout(t, next), depth - 1)
            });
            return plainMatrix(result)
        }
    }

    return _iter(points, depth)
}

export const koch = createPathFn(kochPoints)



// 内拐
const turnin = (p1, p2) => {
    let [x1, y1] = p1
    let [x2, y2] = p2

    let x3 = (x2 - x1) / 3 + x1;
    let y3 = (y2 - y1) / 3 + y1;
    let x4 = (x2 - x1) / 3 * 2 + x1;
    let y4 = (y2 - y1) / 3 * 2 + y1;
    // let x5 = x3 + ((x2 - x1) - (y2 - y1) * Math.sqrt(3)) / 6;
    // let y5 = y3 + ((x2 - x1) * Math.sqrt(3) + (y2 - y1)) / 6;
    // return [p1, [x3, y3], [x5, y5], [x4, y4], p2]

    let p5 = _rotate([x4, y4], [x3, y3], 60)
    return [p1, [x3, y3], p5, [x4, y4], p2]
}

// 三菱
export const mitsubishiPoints = (options) => {
    let { o = [300, 200], r = 200, n = 3, depth = 3, a = 0 } = options

    let points = polarPoints({
        o, r, n, a
    })

    let result = []
    let _iter = (ps, depth) => {

        if (depth === 0) {

            eachNext(ps, (t, index, next) => {
                result.push(...turnin(t, next))
            })
        } else {
            eachNext(ps, (t, index, next) => {
                _iter(turnin(t, next), depth - 1)
            })
        }
    }
    _iter(points, depth)
    return result
}

export const mitsubishi = createPathFn(mitsubishiPoints)
